#pragma once

#include <iostream>
#include <pthread.h>
#include <cstdio>
#include <unistd.h>
#include <queue>
#include <ctime>
#include <cstdlib>

#define NUM 5

//阻塞队列
template<typename T>
class BlockQueue{
  private:
    std::queue<T> q;
    int capacity;
    pthread_mutex_t lock;
    pthread_cond_t full;
    pthread_cond_t empty;
  private:
    //判满
    bool IsFull()
    {
      return q.size() == capacity;
    }
    //判空
    bool IsEmpty()
    {
      return q.size() == 0;
    }
  public:
    BlockQueue(int _capacity = NUM):capacity(_capacity)
    {
      //初始化锁和条件变量
      pthread_mutex_init(&lock, nullptr);
      pthread_cond_init(&full, nullptr);
      pthread_cond_init(&empty, nullptr);
    }
    void Push(const T& in)
    {
      //加锁
      pthread_mutex_lock(&lock);
      while(IsFull()){
        //等待
        pthread_cond_wait(&full, &lock);
      }

      q.push(in);
      //唤醒其他线程
      if(q.size() >= capacity / 2){
        pthread_cond_signal(&empty);
      }
      //解锁
      pthread_mutex_unlock(&lock);
    }
    void Pop(T& out)
    {
      //加锁
      pthread_mutex_lock(&lock);
      while(IsEmpty())
      {
        //等待
        pthread_cond_wait(&empty, &lock);
      }
      out = q.front();
      q.pop();
      //唤醒其他线程
      if(q.size() <= capacity / 2){
        pthread_cond_signal(&full);
      }
      //解锁
      pthread_mutex_unlock(&lock);
    }
    ~BlockQueue()
    {
      //销毁锁和条件变量
      pthread_mutex_destroy(&lock);
      pthread_cond_destroy(&full);
      pthread_cond_destroy(&empty);
    }
};

